#!/bin/bash


function usage() {
  echo "Usage: ./$0 [variable-name]"
  echo "  eg: ./$0 lobby_db_password"
  echo ""
  echo "This script will encode a secret value that can be embedded in ansible"
  echo "and decrypted when ansible runs given the vault password"
  echo ""
  echo "This script expects the secret value to be encrypted to be written" 
  echo "to a file called 'secret'"
  echo "This script expects a second file to contain the ansible vault password"
  echo "named 'vault_password'"
  exit 1
}

variable_name=$1

set -eu

if [ ! -f "secret" ]; then
  echo "Error, file 'secret' should exist containing the secret value to be encrypted"
  exit 1
fi

if [ ! -f "vault_password" ]; then
  echo "Error, file 'vault_password' should exist containing the ansible vault password"
  exit 1
fi

if [ -z "$variable_name" ];then
  usage
fi

if [ ! -z "${2-}" ]; then
  echo "Error, unexpected number of parameters"
  usage
fi

ansible-vault encrypt_string --vault-password-file vault_password "$(cat secret)" --name "$variable_name"

